#include <iostream>
#include <vector>
using namespace std;

vector<vector<int> > Initialize()
{
	cout << "Input number of rows and columns: ";
	int row, column;
	cin >> row >> column;
	
	vector<vector<int> > v;
	v.resize(row);
	for(int i = 0; i < row; i++)
		v[i].resize(column);

	for(int i = 0; i < row; i++)
		for(int j = 0; j < column; j++)
			cin >> v[i][j];

	return v;
}

void PrintMatrixColumnIncreasingly(vector<vector<int> > v, int begin, int end, int line)
{
	//cout << "begin = " << begin << ",end = " << end << ", line = " << line << endl;
	int i = line;
	for(int j = begin; j <= end; j++)
		cout << v[i][j] << " ";
}

void PrintMatrixRowIncreasingly(vector<vector<int> > v, int begin, int end, int line)
{	
	//cout << "begin = " << begin << ",end = " << end << ", line = " << line << endl;
	int j = line;
	for(int i = begin; i <= end; i++)
		cout << v[i][j] << " ";
}

void PrintMatrixColumnDecreasingly(vector<vector<int> > v, int begin, int end, int line)
{	
	//cout << "begin = " << begin << ",end = " << end << ", line = " << line << endl;
	int i = line;
	for(int j = begin; j >= end; j--)
		cout << v[i][j] << " ";
}

void PrintMatrixRowDecreasingly(vector<vector<int> > v, int begin, int end, int line)
{
	//cout << "begin = " << begin << ",end = " << end << ", line = " << line << endl;
	int j = line;
	for(int i = begin; i >= end; i--)
		cout << v[i][j] << " ";
}

void PrintMatrixInCircle(vector<vector<int> > v, int startx, int starty, 
		int endx, int endy)
{
	//Print from left to right.
	PrintMatrixColumnIncreasingly(v,startx,endx,starty); 

	//Print from top to bottom.
	PrintMatrixRowIncreasingly(v,starty+1,endy,endx);

	//Print from right to left.
	PrintMatrixColumnDecreasingly(v,endx-1,startx,endy);

	//Print from bottom to top.
	PrintMatrixRowDecreasingly(v,endy-1,starty+1,startx);
}

void PrintMatrix(vector<vector<int> > v, int rows, int columns)
{
	for(int i = 0; i < rows; i++)
	{
		for(int j = 0; j < columns; j++)
			cout << v[i][j] << "	";
		cout << endl;
	}
}

int main(int argc, char* argv[])
{
	vector<vector<int> > v = Initialize();
	
	int rows = v.size();
	int columns = v[0].size();
	
	//PrintMatrix(v,rows, columns);
	
	int startx = 0;
	int starty = 0;
	int endx = columns - 1;
	int endy = rows - 1;

	while(startx <= endx && starty <= endy)
	{
		PrintMatrixInCircle(v,startx,starty,endx,endy);
		startx++;
		starty++;
		endx--;
		endy--;
	}
}
